//
//  RHVppGroupSetView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/27.
//

#import "RHVppGroupSetView.h"
#import "RHGolobalSetModel.h"
#import "ChoiceInverterTypeView.h"
#import "RHPlantTypeModel.h"

@interface RHVppGroupSetView()<QMUITextFieldDelegate>
@property (nonatomic ,strong) UIView *bgView;

@property (nonatomic, strong) MASConstraint *bgv_constraint;

@property (nonatomic, strong) RHGolobalSetModel *model;

@property (nonatomic, strong) QMUITextField *typeTF;

@property (nonatomic, strong) QMUITextField *chgSocTF;

@property (nonatomic, strong) QMUITextField *dchgSocTF;

@property (nonatomic, strong) QMUITextField *powerTF;

@property (nonatomic, strong) RHPlantTypeModel* curTypeModel;

@property (nonatomic, strong) NSArray *models;
@end
@implementation RHVppGroupSetView

-(instancetype)initWithConfig:(NSArray*)models;
{
    self = [super init];
    if (self) {
        _models = models;
        
        [self setupUI];
        //默认选中一个
        [self getFirstInverterType];

    }
    return self;
}

-(void)setCurTypeModel:(RHPlantTypeModel *)curTypeModel
{
    _curTypeModel = curTypeModel;
    //清空所有值
    self.chgSocTF.text  = nil;
    self.dchgSocTF.text = nil;
    self.powerTF.text   = nil;
    self.typeTF.text = _curTypeModel.plantTypeName;
    [self.models enumerateObjectsUsingBlock:^(RHGolobalSetModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([model.type isEqualToString:self.curTypeModel.plantType]) {
            self.chgSocTF.text  = model.chargeSoc;
            self.dchgSocTF.text = model.dischargeSoc;
            self.powerTF.text   = model.power;
        }
    }];
    
    QMUILabel *powerLab = [self viewWithTag:303];
    if ([self.curTypeModel.plantType isEqualToString:@"S40K LV1.0"]) {
        powerLab.text = [NSString stringWithFormat:@"%@(W)",@"充放电功率".rh_localized];
    }
    //233的最大功率 100kw
    if ([self.curTypeModel.plantType is233DeviceType]||
        [self.curTypeModel.plantType is61DeviceType]) {
        powerLab.text = [NSString stringWithFormat:@"%@(kW)",@"充放电功率".rh_localized];
    }
   
    //如果没有配置过,给默认值
    if (self.chgSocTF.text.length == 0) {
        self.chgSocTF.text = @"100";
        if ([self.curTypeModel.plantType is61DeviceType]) {
            self.chgSocTF.text = @"80";
        }
    }
    if (self.dchgSocTF.text.length == 0) {
        self.dchgSocTF.text = @"50";
        if ([self.curTypeModel.plantType is61DeviceType]) {
            self.dchgSocTF.text = @"10";
        }
    }
    if (self.powerTF.text.length == 0) {
        if ([self.curTypeModel.plantType is61DeviceType]) {
            self.powerTF.text = @"31";
        }
    }
}

-(void)setupUI{
    self.backgroundColor = UIColor.clearColor;
    
    UIView *bgView = kView;
    [self addSubview:bgView];
    self.bgView = bgView;
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.userInteractionEnabled = YES;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
      self.bgv_constraint =  make.top.equalTo(self.mas_bottom).mas_offset(0);
    }];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]init];
    [bgView addGestureRecognizer:tapGesture];
    
    QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D") textAligment:NSTextAlignmentLeft];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.text = @"配置".rh_localized;
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
    }];
    
    
    NSArray *titles = @[@"分组类型",@"强制充电SOC",@"强制放电SOC",@"充放电功率"];
    NSArray *units = @[@"",@"(%)",@"(%)",@"(kW)"];
    __block UIView *lastview;
    [titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *itemView = [self itemViewWithTitle:title unit:units[idx] index:idx];
        [bgView addSubview:itemView];
        if (lastview) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lastview.mas_bottom).offset(15);
                make.left.right.mas_offset(0);
            }];
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
              
                make.top.equalTo(titleLab.mas_bottom).offset(15);
                make.left.right.mas_offset(0);
                
            }];
        }
        lastview = itemView;
    }];
    
    
    QMUIButton *cancelBtn = [[QMUIButton alloc]init];
    [cancelBtn setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    [cancelBtn setTitleColor:kCOLOR_HEX_A(@"#171A1D",0.6) forState:UIControlStateNormal];
    [cancelBtn setCornerRadius:8];
   
    cancelBtn.layer.borderColor = kCOLOR_HEX_A(@"#646566",0.2).CGColor;
    cancelBtn.layer.borderWidth = 1;
    [cancelBtn setBackgroundColor:UIColor.whiteColor];
    [bgView addSubview: cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lastview.mas_bottom).offset(25);
        make.left.mas_offset(15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.height.offset(44);
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [sureBtn setCornerRadius:8];
    [sureBtn setQmui_borderColor:kCOLOR_HEX_A(@"#646566",0.2)];
    [sureBtn setBackgroundColor:CMainColorGreen];
    [bgView addSubview: sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(cancelBtn);
        make.left.equalTo(cancelBtn.mas_right).offset(15);
        make.right.mas_offset(-15);
    }];
    kWeakSelf;
    [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf dismiss];
    }];
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf endEditing:YES];
        [weakSelf saveConfigPara];
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    [self addGestureRecognizer:tap];
    [tap addTarget:self action:@selector(dismiss)];
}

-(UIView*)itemViewWithTitle:(NSString *)title unit:(NSString*)unit index:(NSInteger)index
{
    UIView *bgView = kView;
    kWeakSelf;
    QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D") textAligment:NSTextAlignmentLeft];
    titleLab.text = [NSString stringWithFormat:@"%@%@",title.rh_localized,unit];
    titleLab.tag = 300+index;
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(0);
    }];
    
    QMUITextField *textField = [[QMUITextField alloc]init];
    textField.textInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    textField.font = kSYSTEMFONT(14);
    textField.placeholder = @"请输入".rh_localized;
    textField.placeholderColor = kCOLOR_HEX_A(@"#171A1D", 0.3);
    textField.layer.cornerRadius = 8;
    textField.backgroundColor = kCOLOR_HEX(@"#F3F7FF");
    textField.tag = 100+index;
    [bgView addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(44);
        make.top.equalTo(titleLab.mas_bottom).offset(10);
        make.bottom.mas_offset(0);
    }];
    textField.delegate = self;
    if (index == 0) {
        self.typeTF = textField;
        textField.userInteractionEnabled = NO;
        textField.placeholder = @"请选择".rh_localized;
        UIImageView *arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_down"]];
        [bgView addSubview:arrow];
        [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(18);
            make.centerY.equalTo(textField);
            make.right.mas_offset(-25);
        }];
        
        QMUIButton *btn = [[QMUIButton alloc]init];
        [bgView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf getInverterType];
        }];
    }
    if (index == 1) {
        self.chgSocTF = textField;
    }
    if (index == 2) {
        self.dchgSocTF = textField;
    }
    if (index == 3) {
        self.powerTF = textField;
    }
    return bgView;
}

-(void)saveConfigPara
{
    if (self.typeTF.text.length == 0) {
        [QMUITips showInfo:@"请选择分组类型".rh_localized];
        return;
    }
    if (self.chgSocTF.text.length == 0) {
        [QMUITips showInfo:@"请输入充电SOC".rh_localized];
        return;
    }
    if (self.dchgSocTF.text.length == 0) {
        [QMUITips showInfo:@"请输入放电SOC".rh_localized];
        return;
    }
    if (self.powerTF.text.length == 0) {
        [QMUITips showInfo:@"请输入功率".rh_localized];
        return;
    }
    NSDictionary *para = @{@"chargeSoc":self.chgSocTF.text,
                           @"dischargeSoc":self.dchgSocTF.text,
                           @"power":self.powerTF.text,
                           @"type":self.curTypeModel.plantType
    };
    [QMUITips showLoadingInView:self];
    [RHGolobalSetModel startWithCompletionAPIKey:H_savePlantGroupForceConfig argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized inView:self hideAfterDelay:1];
            self.model.chargeSoc = self.chgSocTF.text;
            self.model.dischargeSoc = self.dchgSocTF.text;
            self.model.power = self.powerTF.text;
            if (self.configBlock) {
                self.configBlock();
            }
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1.2];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark -------- 获取逆变器类型
-(void)getInverterType
{
    kWeakSelf;
    [QMUITips showLoadingInView:self];
    [RHPlantTypeModel startGetWithCompletionAPIKey:H_getInverterType argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [weakSelf showPlantTypeListWith:resultModel.data];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark -------- 获取逆变器类型,取第一个
-(void)getFirstInverterType
{
    kWeakSelf;
    [QMUITips showLoadingInView:self];
    [RHPlantTypeModel startGetWithCompletionAPIKey:H_getInverterType argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *typeArr = resultModel.data;
            if (typeArr.count>0) {
                RHPlantTypeModel *productTypeModel = [typeArr firstObject];//产品类型
               
                RHPlantTypeModel *devTypeModel = [productTypeModel.types firstObject];//设备类型
                RHPlantTypeModel *invTypeModel = [devTypeModel.types firstObject];
                if (invTypeModel.plantType.length>0) {
                    self.curTypeModel = invTypeModel;
                }
            }
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


-(void)showPlantTypeListWith:(NSArray*)typeArr
{
    ChoiceInverterTypeView *choiceView = [[ChoiceInverterTypeView alloc] init];
    choiceView.invTypeList = typeArr;
    choiceView.curInvType = self.curTypeModel.plantType;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(RHPlantTypeModel * _Nonnull model) {
        if (model == nil) {
            return;
        }
        weakSelf.curTypeModel = model;
       
    };
}



-(void)show
{
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    [kAppWindow.rootViewController.view addSubview:self];
    self.frame = kAppWindow.bounds;
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgv_constraint uninstall];
        
        [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
          self.bgv_constraint =  make.bottom.mas_offset(0);
         
        }];
        [UIView animateWithDuration:0.3 animations:^{
            self.backgroundColor = kCOLOR_HEX_A(@"000000", 0.4);
            [self setNeedsLayout];
            [self layoutIfNeeded];
        }];
        
    });
}

-(void)dismiss
{
    [self.bgv_constraint uninstall];
    [self.bgView mas_updateConstraints:^(MASConstraintMaker *make) {
      self.bgv_constraint =  make.top.equalTo(self.mas_bottom).mas_offset(0);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = kCOLOR_HEX_A(@"000000", 0.4);
        [self setNeedsLayout];
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //只能输入正数
    if ([string containsString:@"-"]) {
        return NO;
    }
    
    if ([textField isEqual:self.chgSocTF]||[textField isEqual:self.dchgSocTF]) {
        
        if ([string containsString:@"."]) {
            return NO;
        }
    }
    
    return [NSString checkIsIntOrDecimalNumber:range textFieldContent:textField.text inputString:string];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (![textField isEqual:self.typeTF]&&!self.curTypeModel) {
        [QMUITips showInfo:@"请选择分组类型".rh_localized];
        [textField resignFirstResponder];
    }
}



- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //截止soc  最大值100
    if ([textField isEqual:self.chgSocTF]||[textField isEqual:self.dchgSocTF]) {
        
        if ([textField.text integerValue]>100) {
            textField.text = @"100";
        }
    }
    
    //放电功率
    if ([textField isEqual:self.powerTF]) {
        //最大功率12 kw
        if ([self.curTypeModel.plantType isEqualToString:@"S40K LV1.0"]) {
            if ([textField.text floatValue]>12000) {
                textField.text = @"12000";
            }
        }
        //233的最大功率 100kw
        if ([self.curTypeModel.plantType is233DeviceType]) {
            if ([textField.text floatValue]>125) {
                textField.text = @"125";
            }
        }
       
        //61度电的最大功率 31kw
        if ([self.curTypeModel.plantType isEqualToString:InvType_Sol_Ark_30K_3P_208V]) {
            if ([textField.text floatValue]>30) {
                textField.text = @"30";
            }
        }
        //61度电的最大功率 61kw
        if ([self.curTypeModel.plantType isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {
            if ([textField.text floatValue]>60) {
                textField.text = @"60";
            }
        }
    }
}


-(void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
